"use strict"
var queueArr = [];//全部的分组
var draggers = [];//全部的方块
var isDragging = false;
var isMouseDown = false;
var dragger = null;
var mouseX;
var mouseY;
var draggerLeft;
var draggerTop;
var clone = null;
var DRAG_THRESHOLD = 5;//拖拽阈值
var queueContainer;
var queueActive = {
    // 'border': '1px dashed #808080'
};
var queueUnActive = {
    // 'border': '1px solid #808080'
};
var registerDrag = function (container) {
    queueContainer = container;
    $.each(container.find('.queue'),
        function (index, value) {
            queueArr[index] = $(value);
            draggers[index] = [];
            var elements = $(value).find('.dragger');
            $.each(elements,
                function (_index, _value) {
                    draggers[index][_index] = $(_value);
                });
        });
    for (var i = 0; i < draggers.length; i++)
        for (var j = 0; j < draggers[i].length; j++) {
            draggers[i][j].on('mousedown', dragStart);
        }
    $(document).on('mousemove', dragMove);
    $(document).on('mouseup', dragEnd);
}
//鼠标按下
var dragStart = function (e) {
    e.stopPropagation();
    isMouseDown = true;
    mouseX = e.clientX;
    mouseY = e.clientY;
    dragger = $(this);
}
//鼠标移动
var dragMove = function (e) {
    e.stopPropagation();
    if (!isMouseDown) return;
    var dx = e.clientX - mouseX;
    var dy = e.clientY - mouseY;
    if (isDragging) {
        clone.css({
            left: draggerLeft + dx,
            top: draggerTop + dy
        });
        arrangeDragger();
    } else if (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD) {
        clone = makeClone(dragger);
        draggerLeft = dragger.offset().left - parseInt(dragger.css('margin-left')) - parseInt(dragger.css('padding-left'));
        draggerTop = dragger.offset().top - parseInt(dragger.css('margin-top')) - parseInt(dragger.css('padding-top'));
        clone.css({
            left: draggerLeft,
            top: draggerTop
        });
        queueContainer.append(clone);
        dragger.css('visibility', 'hidden');
        //dragger.css('border', '1px dashed red');
        isDragging = true;
    }
}
//鼠标弹起
var dragEnd = function (e) {
    e.stopPropagation();
    if (isDragging) {
        isDragging = false;
        clone.remove();
        dragger.css('visibility', 'visible');
        // dragger.css('border', '1px solid #000');
    }
    for (var i = 0; i < queueArr.length; i++) queueArr[i].css(queueUnActive);
    isMouseDown = false;
}

//克隆方块
var makeClone = function (source) {
    var res = source.clone();
    res.css({
        position: 'absolute',
        'z-index': 100000
    });
    return res;
}











//整理方块
var arrangeDragger = function () {
    for (var i = 0; i < queueArr.length; i++) queueArr[i].css(queueUnActive);//全部为实线
    var queueIn = findQueue();
    if (queueIn != -1) queueArr[queueIn].css(queueActive);//目标区域为虚线


    var hover = findHover(queueIn);//确定插入的位置
    if (hover == null) return;

    var _hover = hover.hover;//覆盖的块
    var _insert = hover.insert;//覆盖块的左边还是右边
    var queueIdOriginal, drggerIdOriginal;
    var queueIdHover, drggerIdHover;
    //找到源头快的坐标
    for (var i = 0; i < draggers.length; i++) for (var j = 0; j < draggers[i].length; j++) {
        if (draggers[i][j][0] == dragger[0]) {
            queueIdOriginal = i;
            drggerIdOriginal = j;
        }
    }
    draggers[queueIdOriginal].splice(drggerIdOriginal, 1);//从坐标系中移除

    if (_hover) {
        //找到目标块的坐标
        for (var i = 0; i < draggers.length; i++) for (var j = 0; j < draggers[i].length; j++) {
            if (_hover && draggers[i][j][0] == _hover[0]) {
                queueIdHover = i;
                drggerIdHover = j;
            }
        }
        //
        if (_insert == 'left') {
            _hover.before(dragger);
            draggers[queueIdHover].splice(drggerIdHover, 0, dragger);//在队列中插入
        } else {
            _hover.after(dragger);
            draggers[queueIdHover].splice(drggerIdHover + 1, 0, dragger);//在队列中插入
        }
    } else {
        //没有目标位置则还原
        draggers[queueIn].push(dragger);
        queueArr[queueIn].append(dragger);
    }
    
}
//判断clone的块在那个分组中索引
var findQueue = function () {
    var mx = -1,
        pos = -1;
    var cloneTop = clone.offset().top;
    var cloneHeight = clone.height();
    for (var i = 0; i < queueArr.length; i++) {
        var queueTop = queueArr[i].offset().top;
        var queueHeight = queueArr[i].height();
        var val = Math.min(queueTop + queueHeight, cloneTop + cloneHeight) - Math.max(queueTop, cloneTop);
        if (val > mx) {
            mx = val;
            pos = i;
        }
    }
    return pos;
}
//确定相对块的位置
var findHover = function (queueIn) {
    if (queueIn == -1) return null;
    var mx = -1,
        pos = null;
    var cloneTop = clone.offset().top;
    var cloneHeight = clone.height();
    var cloneLeft = clone.offset().left;
    var cloneWidth = clone.width();
    var isOwn = false;
    for (var i = 0; i < draggers[queueIn].length; i++) {
        var _draggerTop = draggers[queueIn][i].offset().top;
        var _draggerHeight = draggers[queueIn][i].height();
        var vertical = Math.min(_draggerTop + _draggerHeight, cloneTop + cloneHeight) - Math.max(_draggerTop, cloneTop);
        var _draggerLeft = draggers[queueIn][i].offset().left;
        var _draggerWidth = draggers[queueIn][i].width();
        var horizontal = Math.min(_draggerLeft + _draggerWidth, cloneLeft + cloneWidth) - Math.max(_draggerLeft, cloneLeft);
        if (vertical <= 0 || horizontal <= 0) continue;
        var s = vertical * horizontal;
        if (s <= cloneHeight * cloneWidth / 3) continue;
        if (draggers[queueIn][i][0] == dragger[0]) {
            isOwn = true;
            continue;
        }
        if (s > mx) {
            mx = s;
            pos = draggers[queueIn][i];
        }
    }
    if (mx < 0) {
        if (isOwn) return null;
        if (draggers[queueIn].length == 0) {
            return {
                'hover': null
            };
        } else {
            var last, index = draggers[queueIn].length - 1;
            while (index >= 0 && draggers[queueIn][index][0] == dragger[0]) index--;
            if (index >= 0) last = draggers[queueIn][index];
            else return {
                'hover': null
            };
            if (cloneLeft >= last.offset().left + last.width()) return {
                'hover': last,
                'insert': 'right'
            };
            else return null;
        }
    } else {
        var posMid = (2 * pos.offset().left + pos.width()) / 2;
        var cloneMid = (2 * clone.offset().left + clone.width()) / 2;
        if (posMid > cloneMid) return {
            'hover': pos,
            'insert': 'left'
        };
        else return {
            'hover': pos,
            'insert': 'right'
        };
    }
}